<!--平台管理-->
<script setup lang="ts">
import {AxiosPromise} from "axios";

defineOptions({
  name: "Platform",
  inheritAttrs: false,
});

import {
	getPlatformPage,
	getPlatformForm,
	savePlatform,
	deletePlatforms,
} from "@/api/platform";

import { PlatformQuery, PlatformForm } from "@/api/platform/types";
import request from "@/utils/request";
import {getDictOptions} from "@/api/dict";
import moment from "moment";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<PlatformQuery>({
  pageNum: 1,
  pageSize: 20,
});

const platformList = ref<[]>();
const platformDictList = ref<OptionType[]>();

const dialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<PlatformForm>({});

const rules = reactive({
  platformKey: [{ required: true, message: "请选择平台", trigger: "change" }],
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getPlatformPage(queryParams)
    .then(({ data }) => {
      platformList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(dicTypeId?: number) {
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改平台";
    getPlatformForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增平台";
    formData.reconciliationSystemCode = 'ECOM'+moment().format('YYMMDDHHmmSS')
  }
}

/**
 * 字典类型表单提交
 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
		savePlatform(formData)
		  .then(() => {
			ElMessage.success("保存成功");
			closeDialog();
			handleQuery();
		  })
		  .finally(() => (loading.value = false));
	}
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}

/**
 * 删除字典类型
 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deletePlatforms(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive<DialogOption>({
  visible: false,
});

/**
 * 获取字典类型的数据项
 *
 * @param typeCode 字典类型编码
 */
function getDictOptionList() {
	getDictOptions('platform').then((response) => {
		platformDictList.value = response.data;
	});
}

function getDictName(key?: string) {
	if (platformDictList != undefined) {
		if (platformDictList.value != undefined) {
			for (let dict of platformDictList.value) {
				if (dict != undefined && dict.value+'' == key) {
					return dict.label
				}
			}
		}
	}
	return ''
}

onMounted(() => {
  handleQuery();
  getDictOptionList();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="平台名称" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="平台名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button
          v-hasPerm="['sys:platform:save']"
          type="success"
          @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
		  		v-hasPerm="['sys:platform:delete']"
          ><i-ep-delete />删除</el-button
        >
      </template>
      <el-table
        size="small"
        :header-row-style="{color: 'dimgray'}"
        v-loading="loading"
        highlight-current-row
        :data="platformList"
        border
        @selection-change="handleSelectionChange"
				:height="platformList && platformList.length > 0 ? 580 : 130"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="平台名称">
          <template #default="scope">
            {{getDictName(scope.row.platformKey)}}
          </template>
        </el-table-column>
        <el-table-column label="对账系统平台编码" prop="reconciliationSystemCode"/>
        <el-table-column label="对账系统平台名称" prop="reconciliationSystemName" />
        <el-table-column label="内部系统平台编码" prop="innerSystemCode"/>
        <el-table-column label="内部系统平台名称" prop="innerSystemName" />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:platform:save']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:platform:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
	  :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
		<el-form-item label="隶属平台" prop="platformKey">
		  <dictionary v-model="formData.platformKey" type-code="platform" clearable/>
		</el-form-item>
        <el-form-item label="对账系统平台编码" prop="reconciliationSystemCode">
          <el-input v-model="formData.reconciliationSystemCode" placeholder="请输入对账系统平台编码" disabled/>
        </el-form-item>
        <el-form-item label="对账系统平台名称" prop="reconciliationSystemName">
          <el-input v-model="formData.reconciliationSystemName" placeholder="请输入对账系统平台名称" clearable/>
        </el-form-item>
        <el-form-item label="内部系统平台编码" prop="innerSystemCode">
          <el-input v-model="formData.innerSystemCode" placeholder="请输入内部系统平台编码" clearable/>
        </el-form-item>
        <el-form-item label="内部系统平台名称" prop="innerSystemName">
          <el-input v-model="formData.innerSystemName" placeholder="请输入内部系统平台名称" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
